
package com.cjb.cloudsystem.jwt;

import cn.hutool.core.util.StrUtil;
import com.cjb.cloudsystem.cache.SysParamsCache;
import com.cjb.common.common.cache.RedisCache;
import com.cjb.common.common.cache.RedisKeys;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;

import static com.cjb.cloudsystem.enums.SysParamsEnum.CAPTCHA_EXPIRE;

/**
 * All rights Reserved, Designed By  chenjinbin
 *
 * @author chenjinbin
 * @Project: fjbd_cjb_bs
 * @Package com.cjb.cloudsecurity.JWT
 * @title TokenUtil
 * @Description
 * @email
 * @date 2023-08-30 15:55
 * @since JDK 1.8
 */
@Component
@AllArgsConstructor
@Slf4j
public class TokenUtil {
    /**
     * 注入缓存仓库
     */
    private final RedisCache redisCache;
    /**
     * 注入控制值的仓库
     */
    private final SysParamsCache sysParamsCache;


    //todo 这是密钥和key 先写死 后期接到区块链的时候补上
    //密钥
    public static final String SUBJECT = "API/TOKEN/CJB/HATELYS/XXXX/kjhsdfsdfoijdspfiojrojotgope";
    //key
    public static final String APPSECRET = "API/TOKEN/CJB/HATELYS/XXXX/kjhsdfsdfoijdspfiojrojotgope";
    //过期时间 读取redis里面的 默认时间 1000
    public static long EXPIRE = 1000 * 1000;

    /**
     * jwt生成token
     *
     * @param
     * @return
     * @author chenjinbin
     * @email 2213859123@qq.com
     * @date 2023-07-12 9:10
     */
    public String geneJsonWebToken(String userId) {
        //缓存中取token值
        String param = sysParamsCache.get(CAPTCHA_EXPIRE.name());
        String value = (String) redisCache.get(RedisKeys.getCaptchaKey(param));
        if (StrUtil.isNotBlank(value)) {
            EXPIRE = Integer.parseInt(value);
        }
        log.info("查看传入的userId: {}",userId);
//        String token = Jwts.builder().setSubject(SUBJECT)
//                .claim("userId", userId)
//                .setIssuedAt(new Date())
//                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
//                .signWith(SignatureAlgorithm.HS256, APPSECRET).compact();
        String token = Jwts.builder().setSubject(SUBJECT)
                .claim("userId", userId)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, APPSECRET).compact();
        return token;
    }

    /**
     * token过期校验
     *
     * @param
     * @return
     * @author chenjinbin
     * @email 2213859123@qq.com
     * @date 2023-07-12 9:10
     */
    public Boolean checkOutJWT(String token) {
        Claims claims = Jwts.parser().setSigningKey(APPSECRET).parseClaimsJws(token).getBody();

        Date now = new Date();
        //过期判断
        if (now.compareTo(claims.getExpiration()) < 0) {
            return false;
        }

        return true;
    }
    /**
     * 解析token
     *
     * @param
     * @return
     * @author chenjinbin
     * @email 2213859123@qq.com
     * @date 2023-07-12 9:10
     */
    public Boolean analysisToken(HttpServletRequest request){
        String accessToken = request.getHeader("Authorization");
        log.info("accessToken is: {}",accessToken);
        if (accessToken == null || !accessToken.startsWith("Bearer ")) {
            return false;
        }
        accessToken = accessToken.substring(7);
        // 过期校验
        if (checkOutJWT(accessToken)){
            log.error("token已过期");
            return false;
        }
        return true;
    }
}
